package com.bbs.config;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.apache.juli.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogConfig {
    private final static Logger log = LoggerFactory.getLogger(LogConfig.class);

    @Pointcut("execution(* com.bbs.controller..*(..))")
    public void requestServer(){

    }

    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
       long start = System.currentTimeMillis();
       ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
       HttpServletRequest request = attributes.getRequest();
       Object result = proceedingJoinPoint.proceed();
       RequestInfo requestInfo = new RequestInfo();
       requestInfo.setIp(request.getRemoteAddr());
       requestInfo.setUrl(request.getRequestURL().toString());
       requestInfo.setHttpMethod(request.getMethod());
       requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
                       proceedingJoinPoint.getSignature().getName()));
//       requestInfo.setResponse(result);
       requestInfo.setTimeCost(System.currentTimeMillis() - start);
       log.info("Request And Response Info      : {}", JSON.toJSONString(requestInfo));
       return result;
    }

    @Data
    public class RequestInfo {
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
//        private Object response;
        private Long timeCost;
    }
}
